<template>
  <div>
    <div>
      <ele-page
        v-loading="loading"
        :formConfig="searchDialog"
        ref="eleTable"
        :operateList="operateList"
        @handleOperateEvent="handleOperateEvent"
        :column="column"
        :getList="getList"
        uniqueId="mesProdOrderTable"
      >
      </ele-page>
    </div>
    <ele-form-drawer
      class="dialog-pack"
      :isLoading="isLoading"
      v-model="formDataDialog"
      v-bind="formDescDialog"
      :request-fn="handleSubmit"
      :visible.sync="visible"
      :key="time"
      :title="title"
      ref="formDrawer"
      size="80%"
    >
      <!-- 下方template标签放入ele-form-drawer中, 并且需要自行修改插槽属性及绑定表单对象的属性 -->
      <template v-slot:planCode>
        <!-- 插槽内容有el-form-item组件包裹 -->
        <el-input v-model="formDataDialog.planCode" readonly :placeholder="$t('mesProdOrder.selectProductOrder')">
          <el-button slot="append" icon="el-icon-search" @click="mesSalesOrderDialogVisible = true"></el-button>
        </el-input>
      </template>
      <template v-slot:prodCode>
        <el-input v-model="formDataDialog.prodCode" readonly disabled :placeholder="$t('mesPmJtmanager.selectMaterial')">
          <!-- <el-button
            slot="append"
            icon="el-icon-search"
            @click="baseGoodsDialogVisible2 = true"
          ></el-button> -->
        </el-input>
      </template>
      <template v-slot:technologyName>
        <el-input v-model="formDataDialog.technologyName" readonly :placeholder="$i18n.t('mesProdOrder.pleaseSelectCraftModeling')">
          <el-button slot="append" icon="el-icon-search" @click="selectTechnology(1)"></el-button>
        </el-input>
      </template>
    </ele-form-drawer>

    <!-- 此组件放到与抽屉平级，理论上不需要修改 -->
    <ele-dialog-table
      :title="$t('mesGateOrderWhite.queryOrder')"
      width="1000px"
      :visible.sync="mesSalesOrderDialogVisible"
      :formConfig="mesSalesOrderSearchDialog"
      :column="mesSalesOrderDialogColumn"
      @getSelectData="getSelectMesSalesOrder"
      :getList="getMesSalesOrderList"
      :hasFooter="hasMesSalesOrderFooter"
    >
      <!-- planEndDate -->
    </ele-dialog-table>
    <ele-dialog-table
      :title="$i18n.t('mesProdOrder.materialQuery')"
      width="1000px"
      :visible.sync="baseGoodsDialogVisible2"
      :formConfig="baseGoodsSearchDialog2"
      :column="baseGoodsDialogColumn2"
      @getSelectData="getSelectBaseGoods2"
      :getList="getBaseGoodsList"
      :hasFooter="hasBaseGoodsFooter"
      :otherParam="{ codeList: this.prodCodesList.join(',') }"
    >
    </ele-dialog-table>
    <ele-dialog-table
      :title="$t('mesProdOrderPlan.modelingQuery')"
      width="1000px"
      :visible.sync="mesTechnologyDialogVisible"
      :column="mesTechnologyDialogColumn"
      @getSelectData="getSelectMesTechnology"
      :getList="getMesTechnologyList"
      :hasFooter="hasMesTechnologyFooter"
      :pagination="false"
      :transFormdata="transFormdatas"
      :initForm="initForm"
    >
    </ele-dialog-table>
    <!--    <el-upload-->
    <!--      ref="upload"-->
    <!--      style="display: none"-->
    <!--      action=""-->
    <!--      accept=".xls, .xlsx"-->
    <!--      :http-request="uploadHttpRequest"-->
    <!--    ></el-upload>-->
    <!-- 下发 -->
    <ele-form-drawer
      class="dialog-pack"
      :isLoading="isLoading"
      v-model="formDataDialog"
      v-bind="formDescDialog_generate"
      :request-fn="generateSubmit"
      :visible.sync="visible_generate"
      :title="title"
      ref="refGenerate"
      :key="keys"
      size="30%"
    >
      <template v-slot:tip>
        <p style="color: red; font-weight: 700; font-size: 16px;">
          {{ tipsTitle }}
        </p>
      </template>
      <template v-slot:technologyName>
        <el-input v-model="formDataDialog.technologyName" readonly :placeholder="$t('mesProdOrder.selectTechnologicalProcess')">
          <el-button slot="append" icon="el-icon-search" @click="selectTechnology(2)"></el-button>
        </el-input>
      </template>
    </ele-form-drawer>

    <!--汇报 -->
    <ele-form-drawer
      class="dialog-pack"
      :isLoading="isLoading"
      v-model="formDataDialog"
      v-bind="formDescDialog_report"
      :request-fn="handleReprt"
      :visible.sync="visible_report"
      :title="title"
      :key="time"
      size="80%"
    >
      <template v-slot:reportList>
        <!-- 插槽内容有el-form-item组件包裹 -->
        <!--点检项-->
        <ele-table-editor ref="table" :isShowAdd="false" :isShowDelete="false" :columns="reportListColumns" v-model="formDataDialog.reportList"> </ele-table-editor>
      </template>
    </ele-form-drawer>

    <!-- 优先级排序 -->
    <el-dialog :title="$t('mesProdOrder.priority')" :visible.sync="showPriorityDialog" width="90%" height="100%" :close-on-click-modal="false">
      <priority v-if="showPriorityDialog" ref="priorityDialog"> </priority>
    </el-dialog>
  </div>
</template>

<script>
import EleTableEditor from 'ele-table-editor'
import { operateList, searchConfig, configformDescDialog, configformDescDialog_generate, configformDescDialog_report, rowConfig, sendThis } from './config'
import { popover } from '@/utils/judge'
import {
  getList,
  rowCreate,
  rowUpdate,
  rowFreezeOrder,
  rowDel,
  rowDetail,
  getProdOrderTypeList,
  getProdOrderStatusList, // 生产$i18n.t('mesProdOrder.orderStatus2')
  getBomVersionNumberList,
  rowGenerate,
  reportOrderByProcess,
  salesDetail,
  printTemplateInfo,
  orderInfoGetBarcode,
  getPrepositionTypeList,
  getModelSetting,
  abnormalClosureOrder,
  batchOrderGenerate,
  getStationCodeList,
  freezeOrderBatch,
  thawOrderBatch
} from '@/api/order/mesProdOrder'
import { mesSalesOrderDialog } from './mixin'
import { baseGoodsDialog2 } from './mixinGoods'
import { mesTechnologyDialog } from './mixinTechnology'
import { getBaseCodeStrategy } from '@/api/common'
import url from '@/axios/url'
import { uniqueKey } from '@/utils/judge.js'
import priority from './components/priority'
import sys from '@/config'
const { minioUrl } = url()
export default {
  name: 'mesProdOrder',
  components: { EleTableEditor, priority },
  mixins: [mesSalesOrderDialog, baseGoodsDialog2, mesTechnologyDialog, configformDescDialog, configformDescDialog_generate, configformDescDialog_report, searchConfig],
  data() {
    const _this = this
    return {
      bomVersionList: [],
      keys: 0,
      time: 1,
      title: null,
      tipsTitle: $i18n.t('mesProdOrder.tipMsg'),
      bomVersionNumberList: [],
      visible: false,
      visible_generate: false, // 下发
      visible_report: false, // 汇报
      generateIds: [], // 下发id
      isLoading: false,
      loading: false,
      editWorkshopList: [],
      editLineList: [],
      formDataDialog: { codeStrategy: '' },
      editLineCode: '',
      // formDataDialog: { codeStrategy: "" },
      time: '0',
      // formDescDialog, //新增修改框
      // searchConfig,
      operateList,
      getList,
      lineList: [], // 线体
      workshopList: [], // 车间
      stationList: [], // 工位
      equipmentList: [], // 工位
      prodCodesList: [],
      orderBarcodeRuleList: [], // 条码规则
      // 列表页字段的绑定配置
      column: [
        {
          type: 'selection',
          fixed: 'left'
        },
        {
          type: 'index',
          label: $i18n.t('common.order'),
          width: 60,
          fixed: 'left'
        },
        // {
        //   prop: "factoryCode",
        //   label: "工厂编码",
        //   minWidth: 120,
        //   showOverflowTooltip: true,
        // },
        {
          prop: 'orderCode',
          label: $i18n.t('mesProdOrder.codeStrategy'),
          minWidth: 240,
          showOverflowTooltip: true,
          fixed: 'left',
          render: (h, { row }) => {
            return popover(row.orderCode, h, '', () => this.goworkDetails(row))

            // return (
            //   <el-link
            //     on={{
            //       click: () => _this.goworkDetails(row)
            //     }}
            //     type="primary">
            //     {row.orderCode}
            //   </el-link>
            // )
          }
        },
        {
          prop: 'planCode',
          label: $i18n.t('mesProdOrder.productionOrderCode'),
          minWidth: 180,
          showOverflowTooltip: true,

          render: (h, { row }) => {
            return popover(row.planCode, h, '', () => this.goDetails(row))
            // return (
            //   <el-link
            //     on={{
            //       click: () => _this.goDetails(row),
            //     }}
            //     type="primary"
            //   >
            //     {row.planCode}
            //   </el-link>
            // );
          }
        },

        {
          prop: 'prodCode',
          label: $i18n.t('mesProdOrder.prodCode'),
          minWidth: 140,
          showOverflowTooltip: true
        },
        {
          prop: 'prodName',
          label: $i18n.t('mesProdOrder.prodName'),
          minWidth: 140,
          showOverflowTooltip: true
        },
        {
          prop: 'orderStatus',
          label: $i18n.t('mesProdOrder.orderStatus2'),
          minWidth: 100,
          showOverflowTooltip: true,
          fixed: 'right',
          optionProp: {
            value: 'value',
            label: 'description'
          },
          option: async (data) => {
            const list = await getProdOrderStatusList()
            return list.data.result
          }
        },
        // {
        //   prop: "priority",
        //   label: "工单优先级",
        //   minWidth: 120,
        //   showOverflowTooltip: true,
        // },
        {
          prop: 'quantity',
          label: $i18n.t('mesProdOrder.planQuantity'),
          minWidth: 100,
          showOverflowTooltip: true
        },
        {
          prop: 'actualQuantity',
          label: $i18n.t('mesProdOrder.actualQuantity'),
          minWidth: 100,
          showOverflowTooltip: true
        },
        {
          prop: 'qualifiedQty',
          label: $i18n.t('mesProdOrder.qualifiedQty'),
          minWidth: 100,
          showOverflowTooltip: true
        },
        {
          prop: 'unqualifiedQty',
          label: $i18n.t('mesProdOrder.unqualifiedQty2'),
          minWidth: 100,
          showOverflowTooltip: true
        },
        {
          prop: 'planBeginDate',
          label: $i18n.t('mesProdOrder.planBeginDate'),
          minWidth: 140,
          showOverflowTooltip: true
        },
        {
          prop: 'planEndDate',
          label: $i18n.t('mesProdOrder.planEndDate'),
          minWidth: 120,
          showOverflowTooltip: true
        },
        {
          prop: 'actualBeginDate',
          label: $i18n.t('mesProdOrder.actualBeginDate'),
          minWidth: 140,
          showOverflowTooltip: true
        },
        {
          prop: 'actualEndDate',
          label: $i18n.t('mesProdOrder.actualEndDate'),
          minWidth: 120,
          showOverflowTooltip: true
        },
        {
          prop: 'workshopName',
          label: $i18n.t('mesProdOrder.workshopName'),
          minWidth: 100
        },
        {
          prop: 'lineName',
          label: $i18n.t('mesProdOrder.lineName2'),
          minWidth: 100,
          showOverflowTooltip: true
        },
        // {
        //   prop: 'stationCode',
        //   label: $i18n.t('mesTeam.workCellCode'),
        //   minWidth: 200,
        //   showOverflowTooltip: true
        // },
        // {
        //   prop: 'stationName',
        //   label: $i18n.t('mesTeam.workCellName'),
        //   minWidth: 200,
        //   showOverflowTooltip: true
        // },
        // {
        //   prop: 'equipmentCode',
        //   label: $i18n.t('mesProdOrderPlan.equipmentCode'),
        //   minWidth: 200,
        //   showOverflowTooltip: true
        // },
        // {
        //   prop: 'equipmentName',
        //   label: $i18n.t('mesProdOrderPlan.equipmentName'),
        //   minWidth: 200,
        //   showOverflowTooltip: true
        // },
        // {
        //   prop: "orderBarcodeRuleName",
        //   label: "条码生成规则",
        //   minWidth: 200,
        //   showOverflowTooltip: true,
        // },
        // {
        //   prop: "isRunning",
        //   label: "是否正在执行接口",
        //   minWidth: 220,
        //   showOverflowTooltip: true,
        //   optionProp: {
        //     value: "value",
        //     label: "description",
        //   },
        //   option: async (data) => {
        //     const list = await getIsRunningList();
        //     return list.data.result;
        //   },
        // },
        // {
        //   prop: "deliveryDate",
        //   label: "交货期",
        //   minWidth: 140,
        //   showOverflowTooltip: true,
        // },
        // {
        //   prop: "slackTime",
        //   label: "交货期宽裕天数",
        //   minWidth: 130,
        //   showOverflowTooltip: true,
        // },
        // {
        //   prop: "prepositionType",
        //   label: "前置工单类型",
        //   minWidth: 100,
        //   showOverflowTooltip: true,
        //   optionProp: {
        //     value: "value",
        //     label: "description",
        //   },
        //   option: async (data) => {
        //     const list = await getPrepositionTypeList();
        //     return list.data.result;
        //   },
        // },
        // {
        //   prop: "prepositionCode",
        //   label: "前置工单号",
        //   minWidth: 150,
        //   showOverflowTooltip: true,
        // },
        {
          prop: 'technologyCode',
          label: $i18n.t('mesProdOrder.technologyCode'),
          minWidth: 150,
          showOverflowTooltip: true
        },
        {
          prop: 'technologyName',
          label: $i18n.t('mesProdOrder.technologyName'),
          minWidth: 150,
          showOverflowTooltip: true
        },
        {
          prop: 'versionNumber',
          label: $i18n.t('mesProdOrder.versionNumber2'),
          minWidth: 180,
          showOverflowTooltip: true
        },
        {
          prop: 'unit',
          label: $i18n.t('mesProdOrder.measureUnit'),
          minWidth: 110,
          showOverflowTooltip: true
        },
        {
          prop: 'unitCode',
          label: $i18n.t('mesProdOrder.measureUnitCode'),
          minWidth: 140,
          showOverflowTooltip: true
        },
        {
          prop: 'prodOrderType',
          label: $i18n.t('mesProdOrder.prodOrderType'),
          minWidth: 150,
          showOverflowTooltip: true,
          optionProp: {
            value: 'value',
            label: 'description'
          },
          option: async (data) => {
            const list = await getProdOrderTypeList()
            return list.data.result
          }
        },
        {
          prop: 'createTime',
          label: $i18n.t('common.createTime'),
          minWidth: 160,
          showOverflowTooltip: true
        },
        {
          prop: 'updateTime',
          label: $i18n.t('common.updateTime'),
          minWidth: 160,
          showOverflowTooltip: true
        },
        {
          prop: 'operate',
          label: $i18n.t('common.operation'),
          width: 230,
          fixed: 'right',
          render: (h, scope) => {
            return <ele-row-operation scope={scope} rowBntNumber={4} rowConfig={rowConfig} onRowOperate={this.rowOperate} />
          }
        }
      ],
      initForm: {},
      multipleSelection: [],
      reportListColumns: [
        {
          // el-table-column 的属性
          label: $i18n.t('common.order'),
          type: 'index',
          width: 60,
          fixed: 'left'
        },
        {
          // el-table-column 的属性
          prop: 'productProcessName',
          label: $i18n.t('mesProdOrder.processName'),
          showOverflowTooltip: true,
          minWidth: 120
          // fixed: "left",
        },
        {
          prop: 'workDate',
          label: $i18n.t('mesProdOrder.workDate'),
          showOverflowTooltip: true,
          minWidth: 120
        },
        {
          prop: 'count',
          label: $i18n.t('mesProdOrder.completedCount'),
          showOverflowTooltip: true,
          minWidth: 140
        },
        {
          prop: 'qualifiedQty',
          label: $i18n.t('mesProdOrder.qualifiedQty2'),
          showOverflowTooltip: true,
          minWidth: 140
        },
        {
          prop: 'unqualifiedQty',
          label: $i18n.t('mesProdOrder.unqualifiedQty3'),
          showOverflowTooltip: true,
          minWidth: 160
        },

        {
          prop: 'laborHours',
          label: $i18n.t('mesProdOrder.laborHours'),
          showOverflowTooltip: true,
          minWidth: 120
        },
        {
          prop: 'machineHours',
          label: $i18n.t('mesProdOrder.machineHours'),
          showOverflowTooltip: true,
          minWidth: 120
        },
        {
          prop: 'otherHours',
          label: $i18n.t('mesProdOrder.otherHours'),
          showOverflowTooltip: true,
          minWidth: 120
        }
      ],
      showPriorityDialog: false
    }
  },
  watch: {
    'formDataDialog.prodCode': {
      handler(val, old) {
        if (val) {
          this.getBomVersionNumberList()
        }
      },
      immediate: true
    },
    'formDataDialog.workshopCode': {
      handler(val, old) {
        if (val) {
          // 根据车间编码查询制造模型列表
          // this.getModelSetting(val);
        }
      },
      immediate: true
    }
  },
  computed: {},
  mounted() {
    sendThis(this)
  },
  created() {
    this.getBaseCodeStrategy()
  },
  activated() {
    this.getBaseCodeStrategy()
  },
  methods: {
    // 开始日期判断
    handleStartDate(val) {
      const { planEndDate } = this.formDataDialog
      if (val && planEndDate) {
        if (new Date(val).getTime() > new Date(planEndDate).getTime()) {
          this.$message.error($i18n.t('mesProdOrder.startDateLimit'))
          this.$set(this.formDataDialog, 'planBeginDate', null)
        }
      }
    },
    handleEndDate(val) {
      const { planBeginDate, orderPlanEndDate } = this.formDataDialog
      if (val && planBeginDate) {
        if (new Date(planBeginDate).getTime() > new Date(val).getTime()) {
          this.$message.error($i18n.t('mesProdOrder.endDateLimit'))
          this.$set(this.formDataDialog, 'planEndDate', null)
        }
      }
      // if (orderPlanEndDate && val) {
      //   if (new Date(val).getTime() > new Date(orderPlanEndDate).getTime()) {
      //     this.$message.error(
      //       `工单计划结束日期应小于或等于订单计划结束日期${orderPlanEndDate}`
      //     );
      //     this.$set(this.formDataDialog, "planEndDate", null);
      //   }
      // }
    },
    selectTechnology(type) {
      if (!this.formDataDialog.planCode && type == 1) {
        return this.$message.error($i18n.t('mesProdOrder.selectProductOrder'))
      }
      this.initForm =
        type == 1
          ? {
              prodCode: this.formDataDialog.prodCode,
              seriesCode: this.formDataDialog.seriesCode,
              workshopCode: this.formDataDialog.workshopCode
            }
          : {
              prodCode: this.multipleSelection[0].prodCode,
              seriesCode: this.multipleSelection[0].seriesCode,
              workshopCode: this.formDataDialog.workshopCode
            }
      this.mesTechnologyDialogVisible = true
    },
    async techSelect() {
      const params = {
        lineCode: this.formDataDialog.lineCode,
        technologyId: this.formDataDialog.technologyId
      }
      const list = await getStationCodeList(params)
      this.stationList = list.data.result
      return list.data.result
    },
    // 跳转详情页
    goDetails(row) {
      this.$router.push({
        path: '/order/mesProdOrderPlan/see',
        query: { id: row.planCode }
      })
      // const state = { title: '工单详情', id: row.planCode }
      // // debugger
      // window.history.pushState({ title: '工单详情' }, '', sys.publicPath + 'order/mesProdOrderPlan/see?id=' + row.planCode)
      // // this.$refs.details.init(row);
    },
    // 跳转销售详情页
    goworkDetails(row) {
      // saleCode
      this.$router.push({
        path: '/order/mesProdOrderPlan/workSee',
        query: {
          id: row.orderCode
        }
      })
      // this.$refs.details.init(row);
    },
    getSalesDetail(salesOrderCode) {
      salesDetail({ salesOrderCode }).then((res) => {
        const result = res.data.result || []
        const prodCodesList = result.map((val) => val.prodCode)
        this.prodCodesList = [...new Set(prodCodesList)]
        console.log('xiao', this.prodCodesList)
      })
    },
    // 表格顶部按钮操作事件
    handleOperateEvent(data) {
      this.title = data.name
      const { codeStrategy } = this.formDataDialog
      const fnc = {
        add: () => {
          this.disableFields(false)
          this.formDataDialog = {
            simulatedType: '1',
            backflushType: '0',
            codeStrategy: codeStrategy
          }
          this.visible = true
        },
        deleteBatch: () => {
          this.$confirm($i18n.t('common.deleteBatch', { name: $i18n.t('mesProdOrder.order') }), $i18n.t('common.tip'), {
            confirmButtonText: $i18n.t('common.ok'),
            cancelButtonText: $i18n.t('common.cancel'),
            type: 'warning'
          }).then(() => {
            const ids = data.rows.map((val) => val.id).join(',')
            this.rowDel(ids)
          })
        },
        // close: () => {
        //   this.$confirm("此操作将强制结束生产工单, 是否继续?", "提示", {
        //     confirmButtonText: "确定",
        //     cancelButtonText: "取消",
        //     type: "warning",
        //   }).then(() => {
        //     const ids = data.rows.map((val) => val.id).join(",");
        //     this.close(ids);
        //   });
        // },
        exportExcel: () => {
          // window.open(
          //   "http://9000.gr817115.m6tfe15g.ceb51d.grapps.cn/file-template/生产工单模板.xls"
          // );

          var url = `${minioUrl}/mes-template/生产工单模板.xls`
          // console.log("aaaaaaa=", url);
          window.open(url)
        },
        batchOrderGenerate: () => {
          this.$confirm($i18n.t('mesProdOrder.batchGiveTip'), $i18n.t('common.tip'), {
            confirmButtonText: $i18n.t('common.ok'),
            cancelButtonText: $i18n.t('common.cancel'),
            type: 'warning'
          }).then(() => {
            const ids = data.rows.map((val) => val.id).join(',')
            batchOrderGenerate(ids).then((res) => {
              const message = res.data.message
              this.$message.success(message || $i18n.t('mesProdOrder.msg6'))
              this.refresh()
            })
          })
        },
        generate: () => {
          if (data.rows.length > 1) {
            const list1 = uniqueKey(data.rows, 'prodCode')
            const list2 = uniqueKey(data.rows, 'seriesCode')
            const list3 = uniqueKey(data.rows, 'stationCode')
            const list4 = uniqueKey(data.rows, 'equipmentCode')
            const list5 = uniqueKey(data.rows, 'lineCode')
            const list6 = uniqueKey(data.rows, 'workshopCode')
            const list7 = uniqueKey(data.rows, 'technologyId')
            if (list1.length > 1) {
              this.$message.warning($i18n.t('mesProdOrder.issueLimit2'))
              return
            }
            if (list2.length > 1) {
              this.$message.warning($i18n.t('mesProdOrder.issueLimit3'))
              return
            }
            if (list3.length > 1) {
              this.$message.warning($i18n.t('mesProdOrder.issueLimit4'))
              return
            }
            if (list4.length > 1) {
              this.$message.warning($i18n.t('mesProdOrder.issueLimit5'))
              return
            }
            if (list5.length > 1) {
              this.$message.warning($i18n.t('mesProdOrder.issueLimit6'))
              return
            }
            if (list6.length > 1) {
              this.$message.warning($i18n.t('mesProdOrder.issueLimit7'))
              return
            }
            if (list7.length > 1) {
              this.$message.warning($i18n.t('mesProdOrder.issueLimit8'))
              return
            }
          }
          const ids = data.rows.map((val) => val.id).join(',')
          this.generateIds = ids
          if (ids != '') {
            const statusFlag = data.rows.some((val) => val.orderStatus != '0')
            if (statusFlag) {
              this.$message.error($i18n.t('mesProdOrder.issueLimit1'))
            } else {
              this.disableFields_generate(false)
              this.formDescDialog_generate.ids = ids // 将IDs传给弹出框
              this.multipleSelection = data.rows
              this.time = new Date().getTime()
              this.formDataDialog = {
                ...this.multipleSelection[0],
                codeStrategy: this.formDataDialog.codeStrategy
                // "workshopCode":''
              }
              this.$nextTick(() => {
                this.visible_generate = true
              })
            }
            // 获取报工类型报工方式
            if (data.rows[0].workshopCode != null && data.rows[0].workshopCode != '' && data.rows[0].workshopCode != undefined) {
              this.getModelSetting(data.rows[0].workshopCode)
            }

            console.log('点击下发输出：', data.rows)
          } else {
            this.$message.error($i18n.t('common.multiple'))
          }
        },
        handlePrint: () => {
          const ids = data.rows.map((val) => val.id).join(',')
          this.generateIds = ids
          if (ids == '') {
            this.$message.error($i18n.t('common.multiple'))
            return false
          }
          this.loading1 = true
          // 获取二维码信息
          orderInfoGetBarcode(ids)
            .then((res3) => {
              console.log('1')
              const id = '1567326884034633730'
              // 获取二维码信息
              const res4 = res3.data.result
              res4.forEach((r) => {
                this.$set(r, 'orderCode', r.orderCode)
                this.$set(r, 'prodCode', r.prodCode)
                this.$set(r, 'quantity', r.quantity)
                if (r.deliveryDate !== '' && r.deliveryDate !== null) {
                  this.$set(r, 'deliveryDate', r.deliveryDate)
                } else {
                  this.$set(r, 'deliveryDate', '')
                }
              })

              printTemplateInfo(id)
                .then((res2) => {
                  this.barcodeInfo = { ...res2.data.result }

                  localStorage.splitPrint = JSON.stringify({
                    ...this.barcodeInfo,
                    values: res4
                  })
                  window.open('/momcommon/splitPrint')
                })
                .catch((err) => {
                  console.log(err)
                })
                .finally(() => {
                  this.loading1 = false
                })
            })
            .finally(() => {
              this.loading1 = false
            })
        },
        reportOrder: () => {
          this.disableFields_report(false)
          this.reportDetail(data.rows[0].id)
          this.visible_report = true
        },
        priorityOrder: () => {
          this.showPriorityDialog = true
        },
        freezeSolution: () => {
          this.$confirm($i18n.t('mesProdOrder.msg8'), $i18n.t('common.tip'), {
            confirmButtonText: $i18n.t('common.ok'),
            cancelButtonText: $i18n.t('common.cancel'),
            type: 'warning'
          }).then(() => {
            const params = data.rows.map((val) => {
              return {
                id: val.id,
                orderStatus: val.orderStatus,
                orderCode: val.orderCode
              }
            })
            console.log(params, '冻结')
            freezeOrderBatch(JSON.stringify(params)).then((res) => {
              const message = res.data.message
              this.$message.success(message || $i18n.t('common.operateSuccess'))
              this.refresh()
            })
          })
        },
        thawSolution: () => {
          this.$confirm($i18n.t('mesProdOrder.msg8'), $i18n.t('common.tip'), {
            confirmButtonText: $i18n.t('common.ok'),
            cancelButtonText: $i18n.t('common.cancel'),
            type: 'warning'
          }).then(() => {
            const params = data.rows.map((val) => {
              return {
                id: val.id,
                orderStatus: val.orderStatus,
                orderCode: val.orderCode
              }
            })
            console.log(params, 'jied')
            thawOrderBatch(JSON.stringify(params)).then((res) => {
              const message = res.data.message
              this.$message.success(message || $i18n.t('common.operateSuccess'))
              this.refresh()
            })
          })
        },

        picking: () => {
          let bool = data.rows.some((ite) => {
            return !['1', '3'].includes(ite.orderStatus)
          })
          if (bool) {
            this.$message.warning($i18n.t('mesProdOrder.msg9'))
            return
          }
          this.$router.push({
            path: '/order/pickingList',
            query: {
              ids: data.rows.map((val) => val.id).join(',')
            }
          })
        }
      }
      fnc[data.handleName]()
    },
    // 表格行操作事件
    rowOperate({ handleName, name, row }) {
      this.title = name
      const fnc = {
        edit: () => {
          this.disableFields(false)
          this.rowDetail(row.id)
          this.visible = true
        },
        detail: () => {
          this.disableFields(true)
          this.rowDetail(row.id)
          this.visible = true
        },
        delete: () => {
          this.$confirm($i18n.t('common.deleteSingle', { name: $i18n.t('mesProdOrder.name2') }), $i18n.t('common.tip'), {
            confirmButtonText: $i18n.t('common.ok'),
            cancelButtonText: $i18n.t('common.cancel'),
            type: 'warning'
          }).then(() => {
            this.rowDel(row.id)
          })
        },
        close: () => {
          if (row.orderStatus == '4') {
            // 工单已完结，不允许冻结
            this.$message.error($i18n.t('mesProdOrder.msg1'))
            return false
          }
          var confirmmmsg = $i18n.t('mesProdOrder.msg2')
          var successmsg = $i18n.t('mesProdOrder.msg3')
          if (row.orderStatus == '5') {
            confirmmmsg = $i18n.t('mesProdOrder.msg4')
            successmsg = $i18n.t('mesProdOrder.msg5')
          }
          this.$confirm(confirmmmsg, $i18n.t('common.tip'), {
            confirmButtonText: $i18n.t('common.ok'),
            cancelButtonText: $i18n.t('common.cancel'),
            type: 'warning'
          }).then(() => {
            this.loading = true
            rowFreezeOrder({
              orderStatus: row.orderStatus,
              id: row.id,
              prodCode: row.prodCode,
              orderCode: row.orderCode
            })
              .then((res) => {
                this.$message.success(successmsg)
                this.refresh(false)
              })
              .finally(() => {
                this.loading = false
              })
            // this.formDataDialog.orderStatus = "5"
          })
        },
        abnormalClosure: () => {
          this.$confirm($i18n.t('mesProdOrder.closeTip'), $i18n.t('common.tip'), {
            confirmButtonText: $i18n.t('common.ok'),
            cancelButtonText: $i18n.t('common.cancel'),
            type: 'warning'
          }).then(() => {
            this.rowAbClose(row.id)
          })
        }
      }
      fnc[handleName]()
    },
    doSubmit({ title, api, data }) {
      // console.log("输出生产工单表单新增的提交123123：",data)
      this.isLoading = true
      api(data)
        .then((res) => {
          const message = res.data.message
          this.$message.success(message || title)
          this.visible = false
          this.visible_generate = false
          this.refresh()
        })
        .finally(() => {
          this.isLoading = false
        })
    },
    // 弹框提交事件
    handleSubmit(data) {
      if (this.isLoading) return // 判断状态
      const params = this.formDataDialog.id ? { title: $i18n.t('common.editSuccess'), api: rowUpdate, data } : { title: $i18n.t('common.addSuccess'), api: rowCreate, data }
      this.doSubmit(params)
    },
    // 下发-弹框提交事件
    generateSubmit(data) {
      // debugger;
      if (this.isLoading) return // 判断状态
      // console.log("this.lineList=", this.lineList);
      const { modelingName } = this.workshopList.find((ite) => ite.modelingCode == data.workshopCode) || {
        modelingName: ''
      }
      data.workshopName = modelingName
      const item_line = this.lineList.find((val) => val.modelingCode == data.lineCode)
      data.lineName = item_line && item_line.modelingName
      const item = this.orderBarcodeRuleList.find((val) => val.code == data.orderBarcodeRuleCode)
      // 工位
      const item_station = this.stationList.find((val) => val.modelingCode == data.stationCode)
      if (item_station) {
        data.stationName = item_station.modelingName
      }
      // 设备
      const item_equipment = this.equipmentList.find((val) => val.equipmentCode == data.equipmentCode)
      if (item_equipment) {
        data.equipmentName = item_equipment.equipmentName
      }
      data.ids = this.generateIds.split(',')
      const params = {
        title: $i18n.t('mesProdOrder.msg6'),
        api: rowGenerate,
        data
      }
      // console.log(params,'====')
      this.doSubmit(params)
    },
    handleReprt(data) {
      if (this.isLoading) return // 判断状态
      const params = {
        title: $i18n.t('mesProdOrder.msg7'),
        api: reportOrderByProcess,
        data
      }
      this.doSubmit(params)
    },
    // 删除
    rowDel(data) {
      this.loading = true
      rowDel(data)
        .then((res) => {
          const message = res.data.message
          this.$message.success(message || $i18n.t('common.deleteSuccess'))
          this.refresh()
        })
        .finally(() => {
          this.loading = false
        })
    },
    // 异常关结工单
    rowAbClose(id) {
      this.loading = true
      abnormalClosureOrder({
        id: id
      })
        .then((res) => {
          const message = res.data.message
          this.$message.success(message || $i18n.t('common.operateSuccess'))
          this.refresh()
        })
        .finally(() => {
          this.loading = false
        })
    },
    // close(data) {
    //   this.loading = true;
    //   close(data)
    //     .then((res) => {
    //       const message = res.data.message;
    //       this.$message.success(message || "关闭成功!");
    //       this.refresh();
    //     })
    //     .finally(() => {
    //       this.loading = false;
    //     });
    // },
    disableFields(flag) {
      this.formDescDialog.disabled = flag
      this.formDescDialog.isShowSubmitBtn = !flag
    },
    disableFields_generate(flag) {
      this.formDescDialog_generate.disabled = flag
      this.formDescDialog_generate.isShowSubmitBtn = !flag
    },
    disableFields_report(flag) {
      this.formDescDialog_report.disabled = flag
      this.formDescDialog_report.isShowSubmitBtn = !flag
    },
    rowDetail(id) {
      rowDetail(id).then((res) => {
        this.formDataDialog = res.data.result
      })
    },
    reportDetail(id) {
      rowDetail(id).then((res) => {
        this.formDataDialog = res.data.result
      })
    },
    // 刷新表格数据
    refresh(isReset = true) {
      this.$refs.eleTable.refresh(isReset)
    },
    // BOM配方版本号
    getBomVersionNumberList() {
      const { prodCode, seriesCode } = this.formDataDialog
      if (!prodCode) {
        this.bomVersionList = []
        return
      }
      const data = {
        materialCode: prodCode,
        serielsCode: seriesCode
      }
      getBomVersionNumberList(data).then((res) => {
        this.bomVersionList = res.data.result
        this.$set(this.formDataDialog, 'bomVersion', '')
      })
    },
    // 判断是否存在编码规则
    getBaseCodeStrategy() {
      getBaseCodeStrategy({
        code: 'prodordercode',
        system: 'default',
        strategyStatus: '1'
      }).then((res) => {
        // console.log("判断是否存在编码规则", res);
        const result = res.data.result
        this.formDataDialog.codeStrategy = Array.isArray(result) && result.length > 0 ? result[0].code : ''
      })
    },

    // 根据车间编码查询制造模型列表
    getModelSetting(workshopCode) {
      getModelSetting({ workshopCode: workshopCode }).then((res) => {
        if (res.data.success) {
          const { reportType, reportWay } = res.data.result.records[0] ?? [{ reportType: '', reportWay: '' }]
          this.$set(this.formDataDialog, 'workshopCode', workshopCode)
          this.$set(this.formDataDialog, 'reportType', reportType)
          this.$set(this.formDataDialog, 'reportWay', reportWay)
          this.$refs.refGenerate.formKey = new Date().getTime()
          console.log('根据车间编码查询制造模型列表：', res.data.result)
        }
      })
    },

    handleClose(done) {
      this.$confirm($i18n.t('mesProdOrder.sureClose'))
        .then((_) => {
          done()
        })
        .catch((_) => {})
    }
  }
}
</script>
